<?php

namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;

class UploadController
{
    /**
     * 文件上传
     */
    public function upload(Request $request)
    {
        $files = $request->file();
        if (empty($files)) {
            return json(['code' => 400, 'msg' => '请选择要上传的文件']);
        }
        
        $file = current($files);
        
        // 验证文件类型
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($file->getUploadMimeType(), $allowedTypes)) {
            return json(['code' => 400, 'msg' => '只允许上传jpg、png、gif格式的图片']);
        }
        
        // 验证文件大小
        if ($file->getSize() > 2 * 1024 * 1024) {
            return json(['code' => 400, 'msg' => '文件大小不能超过2MB']);
        }
        
        // 生成文件名
        $ext = $file->getUploadExtension();
        $fileName = date('Ymd') . '/' . uniqid() . '.' . $ext;
        
        // 移动文件到上传目录
        $uploadPath = public_path() . '/uploads/';
        if (!is_dir($uploadPath . date('Ymd'))) {
            mkdir($uploadPath . date('Ymd'), 0755, true);
        }
        
        $file->move($uploadPath . $fileName);
        
        return json([
            'code' => 0,
            'msg' => '上传成功',
            'data' => [
                'url' => '/uploads/' . $fileName
            ]
        ]);
    }
} 